//
//  Functions.m
//  InitDemo
//
//  Created by 江伟 on 2018/8/14.
//  Copyright © 2018年 weiJiang. All rights reserved.
//

#import "Functions.h"

@implementation Functions

+ (BOOL)isPhoneNumber:(NSString *)number {
    if (number.length == 11) {
        return YES;
    } else {
        return NO;
    }
}

+ (BOOL)isPassward:(NSString *)passward {
    if (passward.length >= 6 && passward.length <= 12) {
        return YES;
    } else {
        return NO;
    }
}

+ (BOOL)isVerfyCode:(NSString *)code {
    if (code.length == 6) {
        return YES;
    } else {
        return NO;
    }
}

+ (NSString *)numberForStr:(NSString *)str {
    NSScanner *scanner = [NSScanner scannerWithString:str];
    [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
    CGFloat number;
    [scanner scanDouble:&number];
    return [NSString stringWithFormat:@"%f",number];
}

+ (NSMutableAttributedString *)attributedStringWithText:(NSString *)text aStr:(NSString *)aStr color:(UIColor *)aColor font:(UIFont *)aFont {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:text];
    NSRange range = [text rangeOfString:aStr];
    if(aColor) {
        [attributedStr addAttribute:NSForegroundColorAttributeName value:aColor range:range];
    }
    if (aFont) {
        [attributedStr addAttribute:NSFontAttributeName value:aFont range:range];
    }
    return attributedStr;
}

+ (NSMutableAttributedString *)underlineAttributedStringWithText:(NSString *)text color:(UIColor *)aColor {
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:text];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, text.length)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:aColor range:NSMakeRange(0, text.length)];
    return attri;
}

+ (void)changeSpaceForLabel:(UILabel *)label withLineSpace:(float)lineSpace WordSpace:(float)wordSpace {
    
    NSString *labelText = label.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(wordSpace)}];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    label.attributedText = attributedString;
}


+ (CGRect)heightForText:(NSString *)text Width:(CGFloat)width font:(UIFont *)font {
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
    return rect;
}

+ (CGRect)widthForText:(NSString *)text height:(CGFloat)height font:(UIFont *)font {
    CGRect rect = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
    return rect;
}


/**
 *  设置段落样式
 *
 *  @param lineSpacing 行高
 *  @param textcolor   字体颜色
 *  @param font        字体
 *
 *  @return 富文本
 */
+ (NSAttributedString *)stringWithParagraphlineSpeace:(CGFloat)lineSpacing
                                                 text:(NSString *)text
                                            textColor:(UIColor *)textcolor
                                             textFont:(UIFont *)font {
    // 设置段落
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    // NSKernAttributeName字体间距
    NSDictionary *attributes = @{ NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@1.5f};
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
    // 创建文字属性
    NSDictionary * attriBute = @{NSForegroundColorAttributeName:textcolor,NSFontAttributeName:font};
    [attriStr addAttributes:attriBute range:NSMakeRange(0, text.length)];
    return attriStr;
}


/**
 *  计算富文本字体高度
 *
 *  @param lineSpeace 行高
 *  @param font       字体
 *  @param width      字体所占宽度
 *
 *  @return 富文本高度
 */
+ (CGFloat)getSpaceLabelHeightwithSpeace:(CGFloat)lineSpeace
                                    text:(NSString *)text
                                withFont:(UIFont*)font
                               withWidth:(CGFloat)width {
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    //    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    /** 行高 */
    paraStyle.lineSpacing = lineSpeace;
    // NSKernAttributeName字体间距
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                          };
    CGSize size = [text boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

+ (NSString *)getTime {
    NSDate *date = [NSDate date]; // 获得时间对象
    NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
    [forMatter setDateFormat:@"HH-mm-ss yyyy-MM-dd"];
    NSString *dateStr = [forMatter stringFromDate:date];
    return dateStr;
}

+ (UIImage *)createImageColor:(UIColor *)color size:(CGSize)size {
    //开启图形上下文
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    //绘制颜色区域
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, size.width, size.height)];
    [color setFill];
    [path fill];
    //    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //    CGContextSetFillColorWithColor(ctx, color.CGColor);
    //    CGContextFillRect(ctx, CGRectMake(0, 0, size.width, size.height));
    //从图形上下文获取图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

+ (UIViewController *)currentVCForView:(UIView *)view {
    UIView *next = view.superview;
    while (1) {
        UIResponder *nextResponder = next.nextResponder;
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
        next = next.superview;
    }
    return nil;
}

+ (NSString *)getMMSSFromSS:(NSString *)time {
    NSInteger seconds = [time integerValue];
    NSString *hour = SF(@"%02ld",seconds / 3600);
    NSString *minute = SF(@"%02ld",(seconds % 3600) / 60);
    NSString *second = SF(@"%02ld",seconds % 60);
    return SF(@"%@:%@:%@",hour,minute,second);
}

+ (UIWindow *)topWindow
{
    UIWindow *topWindow = nil;
    NSArray <UIWindow *>*windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows.reverseObjectEnumerator) {
        if (window.hidden == YES || window.opaque == NO) {
            // 隐藏的 或者 透明的 跳过
            continue;
        }
        if (CGRectEqualToRect(window.bounds, [UIScreen mainScreen].bounds) == NO) {
            // 不是全屏的 跳过
            continue;
        }
        topWindow = window;
        break;
    }
    return topWindow?:[UIApplication sharedApplication].delegate.window;
}
+ (NSString *)timeBeoforeNow:(NSString *)timestamp{
    
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval interval2 = [timestamp doubleValue] - interval;
    long as = (long)interval2*(-1);
    if (as<0) {
        return @"";
    }
    if (as==0) {
        return @"刚刚";
    }
    if (as<60){
        return [NSString stringWithFormat:@"%lu秒前",as];
    }
    if (as<3600){
        //1小时内
        long bs=as/60;
        return [NSString stringWithFormat:@"%lu分钟前",bs];
    }
    if (as<3600*24){
        //24小时内
        long bs=as/3600;
        return [NSString stringWithFormat:@"%lu小时前",bs];
    }
    if (as<86400*7){
        //一个星期内
        long bs=as/86400;
        return [NSString stringWithFormat:@"%lu天前",bs];
    }
    //    if (as<31536000){
    //        long bs=as/2592000;
    //        return [NSString stringWithFormat:@"%lu月前",bs];
    //    }
    
    //    long bs=as/31536000;
    //    return [NSString stringWithFormat:@"%lu年前",bs];
    
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"en_US"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]];
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}
+ (BOOL)isNickName:(NSString *)nickName{
    if (nickName.length>8) {
        return NO;
    }else{
        return YES;
    }
}
+ (BOOL) validateMobile:(NSString *)mobile{
    //手机号以13， 15，18开头，八个 \d 数字字符
    //    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSString *phoneRegex = @"^((1[3,5,8][0-9])|(14[5,7])|(17[0,3,5,6,7,8]|199|166))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
+(NSString *)trimAndLowercase:(NSString *)str{
    NSString *String;
    String = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    return String;
   
}

@end
